# coding=utf-8

##############################################################################
#
# rssfeeder.py
# A class to feed rss from URL, or File
#
# Copyright (c) 2007 Webcore Corp. All Rights Reserved.
#
##############################################################################
""" rssfeeder.py - A class to feed rss from URL, or File

$Id: rssfeeder.py 5 2007-05-06 12:54:22Z shib.ats $
"""

__author__  = 'Atsushi Shibata <shibata@webcore.co.jp>'
__docformat__ = 'plaintext'
__licence__ = 'MIT'

import logging
from datetime import datetime

from feedparser import parse

from utilities import print_exc, urlopen, nifty_formatter
from pluginbase import BaseFeeder

import socket
#socketのタイムアウトを設定
socket.setdefaulttimeout(120)

class RSSFeeder(BaseFeeder):
    """
    RSSをfeedするクラス
    BASIC認証に対応
    feedparserに依存
    """
    def __init__(self, d):
        """
        Feederの初期化method
        設定値を辞書で引数dに渡す
        設定値の辞書からは，以下のキーを読み込む
        
        uri       : RSSのURI,またはファイルのパス。必須
                    ファイルの場合はfile://から始める
        userid    : BASIC認証を行う場合のユーザID
        password  : BASIC認証を行う場合のパスワード
        """
        if 'uri' not in d.keys():
            raise KeyError("""Settings for RSSFeeder must have 'uri'""")
        self.uri = d['uri']
        self.userid = d.get('userid', '')
        self.password = d.get('password', '')

    def feed(self, settings):
        """
        feedを行うmethod
        atom/rssの1アイテムを辞書にし，辞書のリストを返す
        """
        r = urlopen(self.uri, self.userid, self.password)
        feed = parse(r)
        channel = {
                   'link':feed['feed'].get('link', ''),
                   'title':feed['feed'].get('title', ''),
                   'subtitle':feed['feed'].get('subtitle', ''),
                   'author':feed['feed'].get('author', ''),
                  }
        # Element Treeの返してきたエントリを辞書に落とす
        ent = []
        for e in feed['entries']:
            d = {
                 'id':e.get('id', ''),
                 'link':e.get('link', ''),
                 'title':e.get('title', ''),
                 'summary':e.get('summary', ''),
                 'author':e.get('author', ''),
                 'channel':channel,
                 }
            if e.has_key('update_parsed'):
                d['updated'] = datetime(*e['updated_parsed'][:7])
            else:
                d['updated'] = datetime.now()
            
            logout = nifty_formatter(d)
            logging.debug("""%s : reading an feed item:\n%s""" % 
                            (self.__class__.__name__, logout))
            ent.append(d)
        logging.debug("""%s : reading from %s, got %d entries""" % \
                            (self.__class__.__name__, self.uri, len(ent)))
        return tuple(ent)



